package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.Custurn;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.mapper.PlanMapper;
import cn.wolfcode.crm.query.impl.CustomerQuery;
import cn.wolfcode.crm.service.ICustomerService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements ICustomerService {
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    PlanMapper planMapper;

    public void saveOrUpdate(Customer record) {
        if (record.getId() == null) {
            Employee currentUser = UserContext.getCurrentUser();
            //设置录入人
            record.setInputuser(currentUser);
            //设置修改日期
            record.setDate(new Date());
            record.setSn(UserContext.getRandom(16));
            customerMapper.insert(record);
        } else {
            record.setDate(new Date());
            customerMapper.updateByPrimaryKey(record);
        }
    }

    public void delete(Long id) {
        Customer customer = customerMapper.selectByPrimaryKey(id);
        customer.setDate(null);
        customerMapper.updateDate(customer);
        List<Integer> integers = planMapper.selectPlanByCus(id);
        for (Integer i : integers) {
            planMapper.deleteByPrimaryKey((long)i);
        }
    }

    public Customer get(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }


    public PageResult query(CustomerQuery qo) {
        int rows = customerMapper.queryForCount(qo);
        if (rows == 0) {
            new PageResult(rows, Collections.EMPTY_LIST);
        }
        List<Customer> result = customerMapper.queryForList(qo);
        return new PageResult(rows, result);
    }

    public List<Customer> selectAll(CustomerQuery qo) {
        return customerMapper.selectAll(qo);

    }

    public void setInchargeuser(Custurn custurn) {
        Customer customer = new Customer();
        customer.setInchargeuser(custurn.getInchargeuser());
        customer.setId(custurn.getId());
        customerMapper.setInchargeuser(customer);
    }

    public void moveResource(Long id) {
        customerMapper.moveResource(id);
    }

    public void setOfficial(Long id, Long chargeId) {
        customerMapper.setOfficial(id,chargeId);
    }

    public List<Customer> getAll() {
        return customerMapper.getAll();
    }
}
